<?php

namespace app\teacher\controller\subject;

use app\common\controller\Frontend;
use app\common\model\banxi\learn\LearnSkRecord as LearnSkRecordModel;
use app\common\model\banxi\learn\LearnSubjectQuestionAnswerRecord;
use app\common\model\banxi\learn\LearnSubjectQuestionRecord;
use app\common\model\banxi\subject\Subject as SubjectModel;
use app\common\model\banxi\subject\SubjectCourseDict;
use app\common\model\banxi\subject\SubjectGrade;
use app\common\model\banxi\subject\SubjectKnowledge;
use app\common\model\banxi\subject\SubjectQuestion;
use app\common\model\banxi\subject\SubjectTeach;
use app\common\model\banxi\subject\SubjectTeachChapter;
use app\common\model\banxi\trainer\TrainerSubjectNote;
use app\common\service\learn\LearnSkRecordService;

/*
 * 全科课程
 * */
class Subject extends Frontend
{
    protected array $noNeedLogin = [];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }


    /*
     * 全科教材
     * */
    public function dict()
    {
        $SubjectCourseDictMoldel = new SubjectCourseDict();
        $list = $SubjectCourseDictMoldel->where(['del'=>0])->order('sortNum', 'desc')->select();

        $this->ok(__('全科教材'), $list);
    }

    /*
     * 全科年级
     * */
    public function grade()
    {
        $SubjectGradeMoldel = new SubjectGrade();
        $list = $SubjectGradeMoldel->where(['del'=>0])->order('sortNum', 'desc')->select();

        $this->ok(__('全科年级'), $list);
    }

    /*
     * 全科科目
     * */
    public function subject()
    {
        $SubjectModel = new SubjectModel();
        $list = $SubjectModel->where(['del'=>0])->order('sortNum', 'desc')->select();

        $this->ok(__('全科科目'), $list);
    }

    /*
     * 课程列表
     * */
    public function courseList()
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        $param['query']['EQ_status'] = 1;
        //查询条件解析
        $where = get_query($param);

        //获取分页数据
        $pageParams = get_page_params($param);

        $SubjectTeachModel = new SubjectTeach();
        $list = $SubjectTeachModel->where($where)
            ->with(['subject','gradeInfo','courseDictInfo'])
            ->order(['id' => 'desc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit'],
            ])->each(function ($item) {
                $item['chapterNum'] = SubjectTeachChapter::where(['subjectTeachId'=>$item['id']])->count();
                $item['chapterNum'] = SubjectTeachChapter::where(['subjectTeachId'=>$item['id']])->count();
            });
        $this->ok('操作成功', result_row($list));
    }

    /*
     * 知识点
     * */
    public function knowledge()
    {

        $subjectId = $this->request->get('subjectId',0);
        $subjectGradeId = $this->request->get('subjectGradeId',0);

        $where['del'] = 0;
        $where['pid'] = 0;
        if ($subjectId){
            $where['subjectId'] = $subjectId;
        }
        if ($subjectGradeId){
            $where['subjectGradeId'] = $subjectGradeId;
        }
        $SubjectKnowledgeModel = new SubjectKnowledge();
        $list = $SubjectKnowledgeModel->where($where)
            ->order('sortNum','asc')
            ->select();
        if ($list) {
            foreach ($list as $key => $value) {
                $list[$key]['children'] = $SubjectKnowledgeModel->where('pid', $value['id'])->order('sortNum','asc')->select();
            }
        }
        $this->ok('操作成功', $list);
    }

    /*
     * 课程详情
     * */
    public function getCourseDetail()
    {
        $id = $this->request->get('id',0);

        $SubjectTeachModel = new SubjectTeach();
        $info = $SubjectTeachModel
            ->where(['id'=>$id])
            ->find();

        $this->ok('操作成功', $info);
    }

    /*
     * 课程章节
     * */
    public function courseChapter()
    {
        $subjectId = $this->request->get('subjectTeachId',0);
        $SubjectTeachChapterModel = new SubjectTeachChapter();
        $list = $SubjectTeachChapterModel
            ->where(['subjectTeachId'=>$subjectId,'del'=>0,'status'=>1])
            ->order('sortNum','asc')
            ->select();
        if ($list) {
            foreach ($list as $key => $value) {
                $list[$key]['attachment'] = json_decode($value['attachment'],true);;
            }
        }
        $this->ok('课程章节', $list);
    }

    /*
     * 章节题目
     * */
    public function chapterQuestion()
    {
        $subjectChapterId = $this->request->get('subjectChapterId',0);
        $type = $this->request->get('type',1);//1=例题学习;2=随堂联系;
        $SubjectTeachChapterModel = new SubjectTeachChapter();
        $chapter = $SubjectTeachChapterModel
            ->where(['id'=>$subjectChapterId,'del'=>0,'status'=>1])
            ->find();
        if (!$chapter){
//            $this->fail('章节不存在');
            $this->ok('章节题目', true);
        }
        if ($type == 1){
            $question_ids_arr = explode(',',$chapter['beforeClassQuestion']);
        }elseif ($type == 2){
            $question_ids_arr = explode(',',$chapter['inClassQuestion']);
        }
        if (!$question_ids_arr){
            $this->ok('章节题目', true);
        }
        $SubjectQuestionModel = new SubjectQuestion();
        $list = $SubjectQuestionModel
            ->where(['del'=>0,'status'=>1])
            ->whereIn('id',$question_ids_arr)
            ->order('sortNum','asc')
            ->select();
        if ($list) {
            foreach ($list as $key => $value) {
                $list[$key]['option'] = json_decode($value['option'],true);
                $list[$key]['answer'] = json_decode($value['answer'],true);
            }
        }
        $this->ok('章节题目', $list);
    }

    /*
     * 章节知识点
     * */
    public function chapterKnowledge()
    {
        $subjectChapterId = $this->request->get('subjectChapterId',0);
        $SubjectTeachChapterModel = new SubjectTeachChapter();
        $chapter = $SubjectTeachChapterModel
            ->where(['id'=>$subjectChapterId,'del'=>0,'status'=>1])
            ->find();
        if (!$chapter){
//            $this->fail('章节不存在');
            $this->ok('章节知识点', true);
        }
        $SubjectKnowledgeModel = new SubjectKnowledge();
        $knowledge = $SubjectKnowledgeModel
            ->where(['del'=>0])
            ->find();
        $this->ok('章节知识点', $knowledge);
    }

    /*
     * 编辑教材笔记
     * */
    public function editNote()
    {
        $subjectChapterId = $this->request->post('subjectChapterId',0);
        $content = $this->request->post('content', '');

        if (!$subjectChapterId) {
            $this->fail(__('参数错误'));
        }
        $SubjectTeachChapterModel = new SubjectTeachChapter();
        $chapter = $SubjectTeachChapterModel
            ->where(['id'=>$subjectChapterId,'del'=>0,'status'=>1])
            ->find();
        if (!$chapter){
            $this->fail('章节不存在');
        }
        $trainerId = $this->auth->id;
        $TrainerSubjectNoteModel = new TrainerSubjectNote();

        // 查找是否已存在该章节的笔记
        $note = $TrainerSubjectNoteModel->where([
            'subjectTeachId' => $chapter['subjectTeachId'],
            'subjectTeachChapterId' => $subjectChapterId,
            'trainerId' => $trainerId
        ])->find();

        if ($note) {
            // 更新笔记
            $result = $note->save(['content' => $content]);
            if ($result) {
                $this->ok(__('笔记更新成功'));
            } else {
                $this->fail(__('笔记更新失败'));
            }
        } else {
            // 新增笔记
            $data = [
                'subjectTeachId' => $chapter['subjectTeachId'],
                'subjectTeachChapterId' => $subjectChapterId,
                'trainerId' => $trainerId,
                'content' => $content
            ];
            $result = $TrainerSubjectNoteModel->save($data);
            if ($result) {
                $this->ok(__('笔记保存成功'));
            } else {
                $this->fail(__('笔记保存失败'));
            }
        }
    }

    /*
     * 获取教材笔记
     * */
    public function getNote()
    {
        $subjectChapterId = $this->request->get('subjectChapterId',0);
        if (!$subjectChapterId) {
            $this->fail(__('参数错误'));
        }
        $SubjectTeachChapterModel = new SubjectTeachChapter();
        $chapter = $SubjectTeachChapterModel
            ->where(['id'=>$subjectChapterId,'del'=>0,'status'=>1])
            ->find();
        if (!$chapter){
//            $this->fail('章节不存在');
            $this->ok('章节不存在', []);
        }

        $trainerId = $this->auth->id;

        $TrainerSubjectNoteModel = new TrainerSubjectNote();
        $note = $TrainerSubjectNoteModel->where([
            'subjectTeachId' => $chapter['subjectTeachId'],
            'subjectTeachChapterId' => $subjectChapterId,
            'trainerId' => $trainerId,
            'del' => 0,
        ])->find();

        $this->ok('教材笔记', $note);
    }


    /*
     * 获取学生课后作业
     * */
    public function afterClass()
    {
        $skRecordId = $this->request->get('skRecordId',0);

        $LearnSkRecordModel = new LearnSkRecordModel();
        // 获取学习报告数据
        $LearnSkRecord = $LearnSkRecordModel->find($skRecordId);
        if (!$LearnSkRecord){
            $this->fail('学习记录不存在');
        }
        if (!$LearnSkRecord['afterClassQuestion']){
            $this->ok('操作成功', []);
        }
        //获取学生答题记录
        $LearnSubjectQuestionRecordModel = new LearnSubjectQuestionRecord();
        $QuestionRecord = $LearnSubjectQuestionRecordModel
            ->where(['skRecordId'=>$skRecordId,'exerciseType'=>3])
            ->order('id','desc')
            ->find();
        if (!$QuestionRecord){
            $this->ok('操作成功', []);
        }

        $LearnSubjectQuestionAnswerRecordModel = new LearnSubjectQuestionAnswerRecord();
        $QuestionAnswerRecord = $LearnSubjectQuestionAnswerRecordModel
            ->where(['recordId'=>$QuestionRecord['id']])
            ->select();

        $this->ok('操作成功', ['questionList'=>$QuestionAnswerRecord,'recordInfo'=>$QuestionRecord]);
    }


    /*
     * 学生课后作业批改
     * */
    public function afterClassCorrect()
    {
        $recordId = $this->request->post('recordId');
        $answerList = $this->request->post('answerList');

        if (!$recordId){
            $this->fail('记录id不能为空');
        }
        if (!$answerList){
            $this->fail('提交答案不能为空');
        }
        $trainerId = $this->auth->id;

        $LearnSkRecordService = new LearnSkRecordService();
        $result = $LearnSkRecordService->correctSubjectQuestion($recordId, null, null, $answerList);
        if (!$result){
            $this->fail($LearnSkRecordService->getError());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }

    /*
     * 学生课后作业评价
     * */
    public function afterClassComment()
    {
        $recordId = $this->request->post('recordId');
        $comment = $this->request->post('comment');

        if (!$recordId){
            $this->fail('记录id不能为空');
        }
        if (!$comment){
            $this->fail('提交答案不能为空');
        }
        $trainerId = $this->auth->id;

        //获取学生答题记录
        $LearnSubjectQuestionRecordModel = new LearnSubjectQuestionRecord();
        $QuestionRecord = $LearnSubjectQuestionRecordModel
            ->where(['id'=>$recordId,'exerciseType'=>3])
            ->order('id','desc')
            ->find();
        if (!$QuestionRecord){
            $this->fail('记录不存在');
        }

        $QuestionRecord->comment = $comment;
        $QuestionRecord->save();

        $this->ok('操作成功', [], self::NOTIFICATION);
    }
}